import { useRouter } from "next/router";
import { useEffect } from "react";
import { Base64 } from "js-base64";
import { useAuthStore, useChatStore } from "@/store";
import { ILoginRequest } from "@/types/auth";

interface IAutoLogin extends ILoginRequest {
  isAutoLogin: boolean;
}

export function useAutoLogin(): IAutoLogin {
  const router = useRouter();
  const params = new URLSearchParams(router.asPath.split("?")[1]);
  const username = params.get("username") || "";
  const password = params.get("password") || "";
  const userId = params.get("userId") || "";
  const appUser = params.get("appUser") || "";
  const isAutoLogin = !!username && !!password;
  return {
    username,
    password,
    appUser,
    userId,
    isAutoLogin,
  };
}

export default function usePrivateRoute(): any {
  const { token, login } = useAuthStore();
  const router = useRouter();
  const whiteListPage = ["/404"];
  const { username, password, userId, appUser, isAutoLogin } = useAutoLogin();
  const handleAutoLogin = () => {
    if (isAutoLogin) {
      login({
        username: Base64.decode(username),
        password: Base64.decode(password),
        userId: Base64.decode(userId as string),
        appUser: Base64.decode(appUser as string),
      }).then(() => {
        router.replace("/");
      });
    } else if (whiteListPage.includes(router.pathname)) {
      return;
    } else {
      if (!token && router.pathname !== "/login") {
        router.replace("/login");
      }
    }
  };
  useEffect(() => {
    handleAutoLogin();
  }, []);
}
